﻿using ICSharpCode.SharpZipLib.Zip;
using Microsoft.Win32;
using PythonModPacker.helper;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MahApps.Metro.Controls;
using System.Diagnostics;
using MahApps.Metro.Controls.Dialogs;

namespace PythonModPacker
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : MetroWindow
    {
        private FolderBrowserDialog dialog = new FolderBrowserDialog();
        private static String runtimeDir = AppDomain.CurrentDomain.BaseDirectory;
        private String filePath = System.IO.Path.Combine(runtimeDir, "settings.ini");
        private ArrayList modPackPathList = new ArrayList();
        private ZipHelper zip = new ZipHelper();
        private Process process = new Process();

        ~MainWindow()
        {
            process.Close();
        }

        public MainWindow()
        {
            InitializeComponent();
            ReadConfig();
            dialog.Description = "选择相应目录";
            dialog.RootFolder = Environment.SpecialFolder.MyComputer;
            SolvePath();
            process.StartInfo.FileName = "cmd.exe";
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.CreateNoWindow = true;
            process.Start();
        }

        private void ReadConfig()
        {
            pathTextBox.Text = INIHelper.Read("config","path", runtimeDir,filePath);
            devPathTextBox.Text = INIHelper.Read("apolloDeployConfig", "devPath", runtimeDir, filePath);
            syncPathTextBox.Text = INIHelper.Read("apolloDeployConfig", "syncPath", runtimeDir, filePath);
        }

        public void SaveConfig()
        {
            INIHelper.Write("config", "path", pathTextBox.Text, filePath);
            INIHelper.Write("apolloDeployConfig", "devPath", devPathTextBox.Text, filePath);
            INIHelper.Write("apolloDeployConfig", "syncPath", syncPathTextBox.Text, filePath);
        }

        public void SolvePath()
        {
            modPackPathList.Clear();
            DirectoryInfo folder = new DirectoryInfo(pathTextBox.Text);
            foreach (DirectoryInfo projectFolder in folder.GetDirectories())
            {
                ModPackInfo modPackInfo = new ModPackInfo(projectFolder.FullName);
                if (modPackInfo.Validate())
                {
                    modPackPathList.Add(modPackInfo);
                }
            }
            modListBox.Items.Clear();
            foreach (ModPackInfo pack in modPackPathList)
            {
                DirectoryInfo tmp = new DirectoryInfo(pack.rootPath);
                modListBox.Items.Add(tmp.Name);
            }
            DirectoryInfo devPath = new DirectoryInfo(devPathTextBox.Text);
            deployModListBox.Items.Clear();
            foreach (DirectoryInfo projectFolder in devPath.GetDirectories())
            {
                if (projectFolder.Name.StartsWith("."))
                {
                    continue;                    
                }
                deployModListBox.Items.Add(projectFolder.Name);
            }
            statusLabel.Content = String.Format("成功解析所有路径,可供打包的"+ modListBox.Items.Count + "个,可供部署的"+ deployModListBox.Items.Count + "个");
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var text = ShowPathSelectDialog();
            if (text == null)
            {
                return;
            }
            pathTextBox.Text = text;
            SolvePath();
            SaveConfig();
        }

        private void PathTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            
        }

        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            int selected = modListBox.SelectedIndex;
            if (selected == -1)
            {
                await this.ShowMessageAsync("错误", "请选择一个有效项目");
                return;
            }
            statusLabel.Content = "打包中..";
            var modPack = (ModPackInfo)modPackPathList[selected];
            DirectoryInfo directoryInfo = new DirectoryInfo(modPack.rootPath);
            String fileName = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, directoryInfo.Name + ".zip");
            ZipOutputStream zipStream = new ZipOutputStream(File.Create(fileName));
            zip.rootPath = modPack.rootPath;
            zipStream.SetLevel(6);
            var filter = modPack.getFilter();
            zip.ZipDirectory(filter[0],zipStream , fileName);
            zip.ZipDirectory(filter[1],zipStream, fileName);
            zipStream.Finish();
            zipStream.Close();
            statusLabel.Content = "完成打包 " + fileName;
            await this.ShowMessageAsync("成功","打包完成，输出路径: " + fileName);
        }

        private String ShowPathSelectDialog()
        {
            if (dialog.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return null;
            }
            var tmp = dialog.SelectedPath;
            if (tmp == "")
            {
                return null;
            }
            return tmp;
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            var text = ShowPathSelectDialog();
            if (text == null)
            {
                return;
            }
            devPathTextBox.Text = text;
            SaveConfig();
        }

        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            var text = ShowPathSelectDialog();
            if (text == null)
            {
                return;
            }
            syncPathTextBox.Text = text;
            SaveConfig();
        }

        private async void Button_Click_4(object sender, RoutedEventArgs e)
        {
            statusLabel.Content = "开始执行上传";
            process.StandardInput.WriteLine("cd /d "+ syncPathTextBox.Text + "&svn update&svn add *&svn commit -m \""+commitBox.Text+"\"");
            statusLabel.Content = "上传完成";
            await this.ShowMessageAsync( "成功", "SVN操作完成");
        }

        private async void Button_Click_5(object sender, RoutedEventArgs e)
        {
            SolvePath();
            await this.ShowMessageAsync("成功", "刷新完成");
        }

        private void Button_Click_6(object sender, RoutedEventArgs e)
        {
            var selected = deployModListBox.SelectedIndex;
            String name = (String)deployModListBox.Items.GetItemAt(selected);
            var path = System.IO.Path.Combine(devPathTextBox.Text,name);
            var dest = System.IO.Path.Combine(syncPathTextBox.Text, name);
            FileHelper.CopyFolder(path, dest, true);
            statusLabel.Content = "成功复制"+name;
        }

        private void Button_Click_7(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process.Start("https://www.zhanshi123.me");
        }

        private async void Tile_ClickAsync(object sender, RoutedEventArgs e)
        {
            String name = await this.ShowInputAsync("提示", "请输入项目名");
            if(name == null || name.Equals(""))
            {
                return;
            }
            ProjectUtil projectUtil = new ProjectUtil(devPathTextBox.Text,name,serverModSwitch.IsOn);
            projectUtil.GenerateFolder();
            await this.ShowMessageAsync("成功", "创建完成");
        }

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {

        }
    }
}

